﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using VBORT;



namespace BasicMachine
{
    public partial class Form1 : Form
    {
        XmlDocument config = new XmlDocument();
        XmlDocument history = new XmlDocument();
        XmlNodeList nodes;
        XmlNodeList methodNodes;
        XmlNodeList accountNodes;

        ArrayList methodOB = new ArrayList();
        ArrayList accountList = new ArrayList();

        SMS SMSender = new SMS();

        string xmlFilePath = Application.StartupPath + "//config.xml";
        string historyPath = Application.StartupPath + "//history.xml";
        string m_SystemMailList = "rafalechang@gmail.com , SanchesWei@aiptek.com.tw , rcnow@textfree.us";

        const int DOWNMONEY = 60000;

        public Form1()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            config.Load(xmlFilePath);
            history.Load(historyPath);
            loadConfig();

            SignalMonitor();


            bool messageStart = SMSender.Login("0938920062", "sanches0528");

            
            AlertMail.MailFrom = "rs.future.studio@gmail.com";


            Thread ddeOps = new Thread(new ThreadStart(StartReceive));
            ddeOps.Start();


            Thread CheckLimit = new Thread(new ThreadStart(CheckLimitPlace));
            CheckLimit.Start();

            Thread changeMonth = new Thread(new ThreadStart(ChangeMonthPlace));
            changeMonth.Start();

            Thread CheckDDE  = new Thread(new ThreadStart(CheckLive));
            CheckDDE.Start();

            //Thread ddeServer = new Thread(new ThreadStart(StartDDEServer));
           // StartDDEServer();

            Thread ddeOps2 = new Thread(new ThreadStart(StartReceive2));
            ddeOps2.Start();

        }


        public int OrderLot(int asset , int min, int mid)
        {
            int lot;
            lot = asset / (mid *2 + DOWNMONEY);
            if (min > lot)
                lot = min;

            return lot;
        }

        private void SignalMonitor()
        {
            VORT vt = new VORT();
            vt.Add += new VORT.AddEventHandler(vt_Add);
        }


        void vt_Add(List<string> info)
        {
            new Thread((ThreadStart)delegate()
            {
                string signal = string.Join(",", info.ToArray());
                LBox_TSSignal.AppendText(signal);
                StrategyMaster(info);
                LBox_TSSignal.AppendText(Environment.NewLine);
            }).Start();
        }

        private void loadConfig()
        {
            nodes = config.GetElementsByTagName("SimpleConfig");
            methodNodes = config.GetElementsByTagName("Method");
            accountNodes = config.GetElementsByTagName("Account");

            //lab_AccountNO.Text = nodes[0]["AccountNO"].InnerText;
            //accountList.AddRange(nodes[0]["AccountNO"].InnerText.Trim(' ').Split(','));

            Txt_MID2A.Text = methodNodes[0]["MID"].InnerText;
            CKBox_Method2A.Checked = Convert.ToBoolean(methodNodes[0]["Enable"].InnerText);
            Txt_MID2B.Text = methodNodes[1]["MID"].InnerText;
            CKBox_Method2B.Checked = Convert.ToBoolean(methodNodes[1]["Enable"].InnerText);
            Txt_MID1.Text = methodNodes[2]["MID"].InnerText;
            CKBox_Method1.Checked = Convert.ToBoolean(methodNodes[2]["Enable"].InnerText);

            for (int i = 0; i < methodNodes.Count; i++)
            {
                Methods mob = new Methods();
                mob.OrderPlaceDate = methodNodes[i]["OrderDate"].InnerText;
                mob.Method_Name = methodNodes[i]["Name"].InnerText;
                mob.MID_Value = Convert.ToInt32(methodNodes[i]["MID"].InnerText);
                mob.Minimun_Lot = Convert.ToInt32(methodNodes[i]["LotMin"].InnerText);
                mob.Enable = Convert.ToBoolean(methodNodes[i]["Enable"].InnerText);
                mob.Stop_Index = Convert.ToInt32(methodNodes[i]["Stop_Index"].InnerText);
                mob.Limit_Index = Convert.ToInt32(methodNodes[i]["Limit_Index"].InnerText);
                mob.Current_Hold = Convert.ToInt32(methodNodes[i]["Current_Hold"].InnerText);
                mob.excuteMonth = Convert.ToInt32(methodNodes[i]["excuteMonth"].InnerText);
                mob.SpecialRule = methodNodes[i]["SpecialRule"].InnerText;
                mob.Chinese_Name = methodNodes[i]["ChName"].InnerText;
                methodOB.Add(mob);
            }

            for (int i = 0; i < accountNodes.Count; i++)
            {
                string[] enroll = accountNodes[i]["Enroll"].InnerText.Split(',');
                Accounts acc = new Accounts();
                acc.strategys.AddRange(enroll);
                acc.Number = accountNodes[i]["No"].InnerText;
                acc.PhoneNumber = accountNodes[i]["Phone"].InnerText;
                acc.email = accountNodes[i]["email"].InnerText;
                acc.Enable = Convert.ToBoolean(accountNodes[i]["Enable"].InnerText);
                acc.orderLot = Convert.ToInt32(accountNodes[i]["orderLot"].InnerText);
                acc.Asset = Convert.ToInt32(accountNodes[i]["Asset"].InnerText);

                accountList.Add(acc);
                lab_AccountNO.Text += acc.Number + " ,";
            }

            SetContractMonth();
        }

        private void Bt_Save_Click(object sender, EventArgs e)
        {
            methodNodes[0]["MID"].InnerText = Txt_MID2A.Text;
            methodNodes[0]["Enable"].InnerText = CKBox_Method2A.Checked.ToString();
            methodNodes[1]["MID"].InnerText = Txt_MID2B.Text;
            methodNodes[1]["Enable"].InnerText = CKBox_Method2B.Checked.ToString();
            methodNodes[2]["MID"].InnerText = Txt_MID1.Text;
            methodNodes[2]["Enable"].InnerText = CKBox_Method1.Checked.ToString();

            saveToXML();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            saveToXML();

            System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcesses();
            for (int i = 0; i <= process.GetUpperBound(0); i++)
            {
                if (process[i].ProcessName == "BasicMachine")
                {
                    process[i].Kill();
                }
            }

        }


        private void saveToXML()
        {
            for (int i = 0; i < methodNodes.Count; i++)
            {
                methodNodes[i]["Stop_Index"].InnerText = ((Methods)methodOB[i]).Stop_Index.ToString();
                methodNodes[i]["Limit_Index"].InnerText = ((Methods)methodOB[i]).Limit_Index.ToString();
                methodNodes[i]["excuteMonth"].InnerText = ((Methods)methodOB[i]).excuteMonth.ToString();
                methodNodes[i]["OrderDate"].InnerText = ((Methods)methodOB[i]).OrderPlaceDate;
                methodNodes[i]["Current_Hold"].InnerText = ((Methods)methodOB[i]).Current_Hold.ToString();
            }

            for (int i = 0; i < accountNodes.Count; i++)
            {
                accountNodes[i]["orderLot"].InnerText = ((Accounts)accountList[i]).orderLot.ToString();
            }

            config.Save(xmlFilePath);
        }

        private void SaveToHistory(string Name, string Date, string Type, int price, string action, int excuteMonth )
        {
            int currentIndex = lab_Month.Text == excuteMonth.ToString() ? m_IndexValue : m_NextMonthIndexValue;

            XmlNodeList hnode = history.GetElementsByTagName("Order");

            XmlNode nameNode = history.CreateNode("element", "Name", "");
            nameNode.InnerText = Name;
            XmlNode DateNode = history.CreateNode("element", "Date", "");
            DateNode.InnerText = Date;
            XmlNode TypeNode = history.CreateNode("element", "Type", "");
            TypeNode.InnerText = Type;
            XmlNode PriceNode = history.CreateNode("element", "Price", "");
            PriceNode.InnerText = price.ToString();
            XmlNode ActionNode = history.CreateNode("element", "Action", "");
            ActionNode.InnerText = action;
            XmlNode excuteMonthNode = history.CreateNode("element", "excuteMonth", "");
            excuteMonthNode.InnerText = excuteMonth.ToString();
            XmlNode currentIndexNode = history.CreateNode("element", "currentIndex", "");
            currentIndexNode.InnerText = currentIndex.ToString();

            XmlNode OrderNode = history.CreateNode("element", "Order", "");
            OrderNode.AppendChild(nameNode);
            OrderNode.AppendChild(DateNode);
            OrderNode.AppendChild(TypeNode);
            OrderNode.AppendChild(PriceNode);
            OrderNode.AppendChild(ActionNode);
            OrderNode.AppendChild(excuteMonthNode);
            OrderNode.AppendChild(currentIndexNode);

            XmlElement root = history.DocumentElement;
            root.AppendChild(OrderNode);

            history.Save(historyPath);
        }

        private void SetContractMonth()
        {
            bool holding = false;

            foreach (Methods mob in methodOB)
            {
                if (mob.Current_Hold != 0)
                {
                    holding = true;
                    lab_Month.Text = mob.excuteMonth.ToString();

                    lab_NextMonth.Text = GetContractDate().ToString();
                    
                    return;
                }
            }

            if (!holding)
            {
                lab_Month.Text = GetContractDate().ToString();

                lab_NextMonth.Text = lab_Month.Text;
            }


            return;
        }

        private string ReturnCharMonth(string contract)
        {
            char month = Convert.ToChar(64 + Convert.ToInt32(contract.Substring(4, 2)));

            return month + contract.Substring(3, 1);
        }

        private int GetContractDate()
        {

            DateTime dt = DateTime.Now;
            DateTime tD;
            int Wedcounter = 0;
            bool exchangeMonth = false;
            string month;

            for (int i = 1; i <= dt.Day; i++)
            {
                tD = new DateTime(dt.Year, dt.Month, i);

                if (tD.DayOfWeek == DayOfWeek.Wednesday)
                    Wedcounter++;

                //bool MatchCondition = (tD.DayOfWeek == DayOfWeek.Monday) || (tD.DayOfWeek == DayOfWeek.Tuesday);

                //if ((Wedcounter > 1 && MatchCondition) || Wedcounter > 2)
                //{
                //    exchangeMonth = true;
                //    break;
                //}

                if (Wedcounter > 2 && !CB_Delay.Checked)
                {
                    exchangeMonth = true;
                    break;
                }
            }

            if (exchangeMonth)
            {
                DateTime newDt = dt.AddMonths(1);

                if (newDt.Month < 10)
                    month = "0" + newDt.Month;
                else
                    month = newDt.Month.ToString();

                return Convert.ToInt32(newDt.Year + month);
            }

            if (dt.Month < 10)
                month = "0" + dt.Month;
            else
                month = dt.Month.ToString();

            return Convert.ToInt32(dt.Year + month);

        }


        private void Bt_Stop_Click(object sender, EventArgs e)
        {
            List<string> testInfo = new List<string>();

            //testInfo.Add("FITX");
            //testInfo.Add("SE");
            //testInfo.Add("Sell 1 at Market");
            //testInfo.Add("7828");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Sell");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();



            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 7798 Stop");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Short Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();



            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 7920 Stop");
            //testInfo.Add("7920");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("% Trailing Stop");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("SE");
            //testInfo.Add("Sell 1 at Market");
            //testInfo.Add("7910");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Sell");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 7868 Stop");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Short Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();



            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 7868 Stop");
            //testInfo.Add("7868");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Short Lost Exist");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("LE");
            //testInfo.Add("Buy 1 at Market");
            //testInfo.Add("7828");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Buy");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();



            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at 7798 Stop");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Long Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();



            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at 7920 Stop");
            //testInfo.Add("7920");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("% Trailing Stop");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("LE");
            //testInfo.Add("Buy 1 at Market");
            //testInfo.Add("7910");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Buy");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at 7868 Stop");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Long Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();



            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at 7868 Stop");
            //testInfo.Add("7868");
            //testInfo.Add("400");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("2010/3/18 上午 06:58:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Long Lost Exist");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();




            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 6767 Stop");
            //testInfo.Add("Method2_B(20,6,100,60,60,100)");
            //testInfo.Add("Short Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 6622 Limit");
            //testInfo.Add("Method2_B(20,6,100,60,60,100)");
            //testInfo.Add("Short Gain Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at Limit");
            //testInfo.Add("6722");
            //testInfo.Add("109");
            //testInfo.Add("2009/8/20 上午 06:58:00");
            //testInfo.Add("2009/8/20 上午 08:50:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Buy");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            ////testInfo.Clear();

            //testInfo.Clear();

            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 6767 Stop");
            //testInfo.Add("Method2_B(20,6,100,60,60,100)");
            //testInfo.Add("Short Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //testInfo.Add("FITX");
            //testInfo.Add("SX");
            //testInfo.Add("Buy 1 at 6622 Limit");
            //testInfo.Add("Method2_B(20,6,100,60,60,100)");
            //testInfo.Add("Short Gain Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //StopMonitor(6767);

            //LimitMonitor(6622);

            //testInfo.Add("FITX");
            //testInfo.Add("LE");
            //testInfo.Add("Buy 1 at Market");
            //testInfo.Add("6722");
            //testInfo.Add("109");
            //testInfo.Add("2009/8/20 上午 06:58:00");
            //testInfo.Add("2009/8/20 上午 08:50:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Buy");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at 6622 Stop");
            //testInfo.Add("Method2_B(20,6,100,60,60,100)");
            //testInfo.Add("Long Lost Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();


            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at 6822 Limit");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Long Gain Exit");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at Stop");
            //testInfo.Add("6722");
            //testInfo.Add("109");
            //testInfo.Add("2009/8/20 上午 06:58:00");
            //testInfo.Add("2009/8/20 上午 08:50:00");
            //testInfo.Add("Method2_A(20,6,100,60,60,100)");
            //testInfo.Add("Sell");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //testInfo.Clear();

            //StopMonitor(6622);

            ////LimitMonitor(6822);

            //testInfo.Add("FITX");
            //testInfo.Add("LE");
            //testInfo.Add("Buy 1 at Market");
            //testInfo.Add("6722");
            //testInfo.Add("109");
            //testInfo.Add("2009/8/20 上午 06:58:00");
            //testInfo.Add("2009/8/20 上午 08:50:00");
            //testInfo.Add("Method1(20,6,100,60,60,100)");
            //testInfo.Add("Buy");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //testInfo.Add("FITX");
            //testInfo.Add("LX");
            //testInfo.Add("Sell 1 at Market");
            //testInfo.Add("7367");
            //testInfo.Add("400");
            //testInfo.Add("2009/8/20 上午 06:58:00");
            //testInfo.Add("2009/8/20 上午 08:50:00");
            //testInfo.Add("Method1(20,6,100,60,60,100)");
            //testInfo.Add("Sell");
            //testInfo.Add(@"C:\Program Files\Omega Research\MyWork\RealTimeTaiwan.orw");
            //testInfo.Add("5 min.");

            //StrategyMaster(testInfo);

            //testInfo.Clear();

            //StopMonitor(6622);

            //LimitMonitor(6822);
        }

        private void CB_Delay_CheckedChanged(object sender, EventArgs e)
        {
            SetContractMonth();
        }



    }
}